/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.server.data;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bioteam.appweb.Config;
import net.bioteam.appweb.gwt.apps.server.UserFileConverter;
import net.bioteam.appweb.gwt.apps.server.program.ProgramHandler;
import net.bioteam.common.user.User;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

public class FileUpload extends HttpServlet
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		User user = (User) req.getSession().getAttribute("user");
		String username = user.getName();
		String path = null;
		String nodeID=null;
		List<File> tmpfiles = new ArrayList<File>();
		List<File> destfiles = new ArrayList<File>();
		try
		{
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = null;
			iter = upload.getItemIterator(req);
			while (iter.hasNext())
			{
				FileItemStream item = iter.next();
				String name = item.getFieldName();
				InputStream stream = item.openStream();

				String filename = item.getName();
				if (filename != null)
				{
					filename = FilenameUtils.getName(filename.trim());
				}

				if (item.isFormField())
				{
					if (name.equals("path"))
						path = Streams.asString(stream).trim();
					else if (name.equals("nodeID"))
						nodeID=Streams.asString(stream).trim();
				} else
				{
					if (filename == null || filename.length() == 0)
						continue;
					File file = new File(Config.USER_TMP + File.separator + username + File.separator + filename);
					BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
					Streams.copy(stream, out, true);
					tmpfiles.add(file);
				}
			}

			if (path == null)
			{
				sentError("No path is specifiied", nodeID, tmpfiles, destfiles, resp);
				return;
			}
			if (nodeID == null)
			{
				sentError("No node ID is specifiied", nodeID, tmpfiles, destfiles, resp);
				return;
			}
			File dir = null;
			if (user.isAdmin())
			{
				dir = new File(UserFileConverter.clientPathToRealPath(path, username));
			} else
			{
				dir = new File(UserFileConverter.dataClientPathToRealPath(path, username));
			}
			if (!dir.exists())
			{
				sentError( "Can not find the specified path", nodeID, tmpfiles, destfiles, resp);
				return;
			}
			for (File file : tmpfiles)
			{
				File destfile = new File(dir + File.separator + file.getName());
				if (destfile.exists())
				{
					sentError( "File error: there is already a file with the same name", nodeID, tmpfiles, destfiles, resp);
					return;
				}
				try
				{
					FileUtils.moveFile(file, destfile);
				} catch (Exception e)
				{
					sentError("File error: can not move file to user file directory. "+e.getMessage(), nodeID, tmpfiles, destfiles, resp);
					return;
				}
				destfiles.add(destfile);
			}

			String msg = ProgramHandler.getUploadRetMessage(true, "success", nodeID);
			resp.setContentType("text/html");
			resp.setContentLength(msg.length());
			resp.getWriter().write(msg);
		} catch (Exception e)
		{
			sentError(e.getMessage(), nodeID, tmpfiles, destfiles, resp);
		}

	}
	
	private void sentError(String message, String nodeID, List<File> tmpfiles, List<File> destfiles, HttpServletResponse resp) throws IOException
	{
		String msg = ProgramHandler.getUploadRetMessage(false, message, nodeID);
		resp.setContentType("text/html");
		resp.setContentLength(msg.length());
		resp.getWriter().write(msg);
		for (File file : tmpfiles)
		{
			file.delete();
		}
		for (File file : destfiles)
		{
			file.delete();
		}
	}

}
